<template>
  <!-- app-container  -->
  <div
    class="standingbook-common"
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
  >
    <lb-layout>
      <Title name="公共机构概况" :line="false">
        <el-row>
          <el-col :span="6">
            <sumCom :publicnum="publicnum"></sumCom>
          </el-col>
          <el-col :span="9">
            <pieChart
              ref="pieData1"
              v-if="Object.keys(pieData.data1).length > 0"
              :pieData="pieData.data1"
              @clickPie="clickPie"
            />
          </el-col>
          <el-col :span="9">
            <pieChart
              ref="pieData2"
              v-if="Object.keys(pieData.data2).length > 0"
              :pieData="pieData.data2"
            />
          </el-col>
        </el-row>
      </Title>
      <Title name="公共机构列表" :line="false" class="mt20">
        <div class="box-content">
          <aps-form
            :config="apsForm.formConfig"
            :model="apsForm.formData"
            :formRef="apsForm.formRef"
            :labelWidth="apsForm.labelWidth"
            ref="form"
          ></aps-form>
          <lb-table
            :column="tableData.column"
            height="300"
            :data="tableData.data"
            pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 30, 40]"
            :pager-count="5"
            :current-page.sync="currentPage"
            :total="total"
            :page-size="pageSize"
            @size-change="handleSizeChange"
            @p-current-change="handleCurrentChange"
          >
          </lb-table>
        </div>
      </Title>
    </lb-layout>
    <component
      :is="modelName"
      :modelWay="modelWay"
      :id="id"
      :visible.sync="show"
      @close="close"
    ></component>
  </div>
</template>

<script>
import { deepClone } from "@/utils/index";
import detail from "@/views/work/standingbook/common/components/detail.vue";
import bulk from "@/views/work/standingbook/components/bulkimport.vue";
import sumCom from "@/views/work/standingbook/common/components/sum.vue";
import pieChart from "@/views/work/standingbook/common/components/pieChart.vue";
import {
  getInstitutionslist,
  getInstitutionspie,
} from "@/api/standingbook/common.js";
import auth from "@/plugins/auth";
export default {
  components: {
    detail,
    bulk,
    sumCom,
    pieChart,
  },
  dicts: [
    "organization_catagroy",
    "organization_type",
    "reporting_status",
    "administrative_division",
  ],
  data() {
    return {
      show: false,
      modelName: "",
      modelWay: "",
      id: "",
      currentPage: 1,
      pageSize: 10,
      total: 0,
      apsForm: {
        formRef: "form",
        labelWidth: "120px",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            // organizationStructureCode: {
            //   typeName: "el-input",
            //   placeholder: "请输入组织结构代码",
            // },
            unifiedSocialCreditCode: {
              typeName: "el-input",
              placeholder: "请输入信用代码",
            },
            companyName: {
              typeName: "el-input",
              placeholder: "请输入机构名称",
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            {
              label: "新增",
              type: "primary",
              plain: true,
              typeName: "el-button",
              size: "small",
              icon: "el-icon-plus",
              display: true,
              click: this.handleAdd,
            },
            {
              label: "批量导入",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-back",
              display: true,
              click: this.handleImport,
            },
          ],
        },
      },
      tableData: {
        column: [
          {
            prop: "companyName",
            label: "机构名称",
            showOverflowTooltip: true,
          },
          {
            prop: "organizationType",
            label: "机构类型",
            width: "150",
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.organization_type}
                    value={scope.row.organizationType}
                  />
                </div>
              );
            },
          },
          {
            prop: "administrativeDivision",
            label: "行政区划",
            width: "140",
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.administrative_division}
                    value={scope.row.administrativeDivision}
                  />
                </div>
              );
            },
          },
          // {
          //   prop: "organizationStructureCode",
          //   label: "组织结构代码",
          //   width: "150",
          // },
          {
            prop: "unifiedSocialCreditCode",
            label: "统一社会信用代码",
            width: "220",
            showOverflowTooltip: true,
          },
          {
            prop: "",
            label: "单位地址",
            width: "260",
            render: (h, scope) => {
              let a = "";
              let p1 =
                scope.row.companyAddressProvince == null
                  ? ""
                  : scope.row.companyAddressProvince;
              let p2 =
                scope.row.companyAddressCity == null
                  ? ""
                  : scope.row.companyAddressCity;
              let p3 =
                scope.row.companyAddressCounty == null
                  ? ""
                  : scope.row.companyAddressCounty;
              let p4 =
                scope.row.companyAddressTown == null
                  ? ""
                  : scope.row.companyAddressTown;
              let p5 =
                scope.row.companyAddressStreet == null
                  ? ""
                  : scope.row.companyAddressStreet;
              let p6 =
                scope.row.companyAddressHouseNum == null
                  ? ""
                  : scope.row.companyAddressHouseNum;
              a = p1 + p2 + p3 + p4 + p5 + p6;
              return h("div", {}, a);
            },
          },
          {
            prop: "phone",
            label: "联系电话",
            width: "150",
          },
          {
            prop: "status",
            label: "状态",
            width: "120",
            showOverflowTooltip: true,
            align: "center",
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.reporting_status}
                    value={scope.row.status}
                  />
                </div>
              );
            },
            // render: (h, scope) => {
            //   let testType = scope.row.status;
            //   let typeArr = this.dict.type.reporting_status;
            //   let typeName = "";
            //   typeArr.forEach((element) => {
            //     if (element.value == testType) {
            //       typeName = element.label;
            //     }
            //   });
            //   return h("div", {}, typeName);
            // },
          },
          {
            label: "操作",
            width: "200",
            fixed: "right",
            render: (h, scope) => {
              let that = this;
              let a, b, c, d, e, f, g;
              let inline = {
                float: "left",
                // display: "flex",
                // justifyContent: "space-around",
                // alignItems: "flex-start",
              };
              if (scope.row.status == 0) {
                a = (
                  <el-button
                    v-hasPermi={["energy:institutions:edit"]}
                    type="text"
                    size="small"
                    icon="el-icon-upload2"
                    onClick={() => {
                      that.handlerReported(deepClone(scope.row));
                    }}
                  >
                    提交
                  </el-button>
                );
                c = (
                  <el-button
                    v-hasPermi={["energy:institutions:edit"]}
                    type="text"
                    size="small"
                    icon="el-icon-edit"
                    onClick={() => {
                      that.handlerEdit(deepClone(scope.row));
                    }}
                  >
                    编辑
                  </el-button>
                );
              } else {
                a = <div style="display:none"></div>;
                c = <div style="display:none"></div>;
              }
              if (scope.row.status == 1 || scope.row.status == 2) {
                if (that.$store.state.user.id === 1) {
                  // 超级管理员无视一切
                  b = (
                    <el-button
                      v-hasPermi={["energy:institutions:audit"]}
                      type="text"
                      size="small"
                      icon="el-icon-document-checked"
                      onClick={() => {
                        that.handerAudit(deepClone(scope.row));
                      }}
                    >
                      审核
                    </el-button>
                  );
                } else {
                  // 同一行政区划内才可以审核
                  // 处于区县待审核状态
                  if (scope.row.status == 1) {
                    // 该用户必须是区县级的审核人员
                    if (that.$store.state.user.administrativeDivision == "2") {
                      b = (
                        <el-button
                          // 数据权限控制该用户是否有审核的权力
                          v-hasPermi={["energy:institutions:audit"]}
                          type="text"
                          size="small"
                          icon="el-icon-document-checked"
                          onClick={() => {
                            that.handerAudit(deepClone(scope.row));
                          }}
                        >
                          审核
                        </el-button>
                      );
                    } else {
                      b = <div style="display:none"></div>;
                    }
                    // 处于地市待审核状态
                  } else if (scope.row.status == 2) {
                    // 该用户必须是地市级的审核人员
                    if (that.$store.state.user.administrativeDivision == "1") {
                      b = (
                        <el-button
                          // 数据权限控制该用户是否有审核的权力
                          v-hasPermi={["energy:institutions:audit"]}
                          type="text"
                          size="small"
                          icon="el-icon-document-checked"
                          onClick={() => {
                            that.handerAudit(deepClone(scope.row));
                          }}
                        >
                          审核
                        </el-button>
                      );
                    } else {
                      b = <div style="display:none"></div>;
                    }
                  }
                }
              } else {
                b = <div style="display:none"></div>;
              }
              if (scope.row.status == 3) {
                f = (
                  <el-button
                    v-hasPermi={["energy:institutions:report"]}
                    type="text"
                    size="small"
                    icon="el-icon-document-checked"
                    onClick={() => {
                      that.handleUp(deepClone(scope.row));
                    }}
                  >
                    上报
                  </el-button>
                );
              } else {
                f = <div style="display:none"></div>;
              }
              if (scope.row.status == 4) {
                e = (
                  <el-button
                    v-hasPermi={["energy:manage:list"]}
                    type="text"
                    size="small"
                    icon="el-icon-edit-outline"
                    onClick={() => {
                      that.$router.push({
                        name: "CarbonInspect",
                        query: {
                          id: scope.row.id,
                        },
                      });
                    }}
                  >
                    核查
                  </el-button>
                );
                d = (
                  <el-button
                    v-hasPermi={["energy:institutions:query"]}
                    type="text"
                    size="small"
                    icon="el-icon-search"
                    onClick={() => {
                      that.handlerLook(deepClone(scope.row));
                    }}
                  >
                    查看
                  </el-button>
                );
              } else {
                e = <div style="display:none"></div>;
                d = <div style="display:none"></div>;
              }
              if (scope.row.status == 5 || scope.row.status == 6) {
                g = (
                  <el-button
                    v-hasPermi={["energy:institutions:confirm"]}
                    type="text"
                    size="small"
                    icon="el-icon-check"
                    onClick={() => {
                      that.handleComit(deepClone(scope.row));
                    }}
                  >
                    确认
                  </el-button>
                );
              } else {
                g = <div style="display:none"></div>;
              }
              // }
              return (
                <div style={inline}>
                  {a}
                  {b}
                  {c}
                  {d}
                  {e}
                  {f}
                  {g}
                </div>
              );
            },
          },
        ],
        data: [],
      },
      pieData: {
        data1: {},
        data2: {},
      },
      publicnum: 0,
      fatherPielist: [],
    };
  },
  created() {},
  mounted() {
    this.judgePermi();
    this.getMymsg();
    setTimeout(() => {
      this.getPiedata();
    }, 100);
    this.initData({}, true);
  },
  methods: {
    // 路由参数判断
    judgeRoutequery() {
      if (this.$route.query.choseOne == "1") {
        let arr = this.tableData.data;
        let obj = {};
        if (arr.length > 0) {
          function findFirst(item) {
            return item.status == 4 ? item : undefined;
          }
          obj = arr.find(findFirst);
        }
        if (obj != undefined && Object.keys(obj).length > 0) {
          this.$router.push({
            name: "CarbonInspect",
            query: {
              id: obj.id,
            },
          });
        }
      }
    },
    // 权限判断
    judgePermi() {
      if (auth.hasPermi("energy:institutions:add")) {
        this.apsForm.formConfig.formSoltButton[2].display = false;
        this.apsForm.formConfig.formSoltButton[3].display = false;
      } else {
      }
    },
    // 获取我的信息
    getMymsg() {
      // console.log(this.$store.state.user, "用户信息");
    },
    async initData(data, flag) {
      let that = this;
      let query = {
        ...data,
      };
      query.pageNum = that.currentPage;
      query.pageSize = that.pageSize;
      that.$store.commit("app/updateApiCount", "add");
      await getInstitutionslist(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res?.rows ?? [];
          that.total = res?.total ?? 0;
          if (flag) {
            setTimeout(() => {
              that.judgeRoutequery();
            }, 1000);
          }
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!20030");
        });
    },
    // 搜索
    handlerSearchDetail() {
      const { ...other } = this.$refs?.form?.getFieldsValue();
      const data = {
        ...other,
      };
      this.initData(data);
    },
    //重置
    handleReset() {
      this.$refs?.form?.resetFields();
      this.initData();
    },
    // 新增
    handleAdd() {
      this.showModel("detail", "", "add");
    },
    // 批量导入
    handleImport() {
      this.showModel("bulk", "", "");
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    /* 饼图数据处理和操作 */
    // resetpieData(flage) {
    //   this.pieData["data" + flage] = {};
    // },
    async getPiedata() {
      // this.resetpieData("1");
      // this.resetpieData("2");
      await getInstitutionspie()
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          } else {
            if (res.code == 200) {
              if (res.data != null) {
                this.publicnum = res?.data?.num ?? 0;
                this.fatherPielist = res?.data?.list ?? [];
                if (this.fatherPielist.length > 0) {
                  let arr = this.pieDatadeal(this.fatherPielist);
                  if (arr) {
                    this.getPiedata1(arr);
                  }
                  let brr = this.fatherPielist[0].innerList;
                  if (brr.length > 0) {
                    let crr = this.pieDatadeal(brr);
                    if (crr) {
                      this.getPiedata2(crr);
                    }
                  } else {
                    this.getPiedata2([]);
                  }
                } else {
                  this.getPiedata1([]);
                  this.getPiedata2([]);
                }
              } else {
                this.publicnum = 0;
                this.getPiedata1([]);
                this.getPiedata2([]);
              }
            }
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20030");
        });
    },
    getPiedata1(arr) {
      let color = ["#C44729", "#4F5467", "#E1B228", "#3669D4"];
      let dataArr = arr;
      let title = "";
      let pieId = "standingbookpieChartsone";
      let legend = {
        orient: "vertical",
        top: "35%",
        padding: 0,
        left: "15%",
        icon: "circle",
        itemGap: 3,
        textStyle: {
          color: "#8C8C8C",
          fontFamily: "PingFang-SC-Regular, PingFang-SC",
          fontWeight: 400,
          lineHeight: 17,
        },
      };
      let data = {
        color: color,
        dataArr: dataArr,
        // title: title,
        legend: legend,
        pieId: pieId,
        roseType: "",
        radius: ["40%", "70%"],
        position: "center",
        selectedMode: "single",
      };
      this.pieData.data1 = data;
    },
    getPiedata2(arr) {
      let color = ["#5B8FF9", "#5AD8A6", "#5D7092"];
      let dataArr = arr;
      // [
      //   { value: 100, name: "社会团体" },
      //   { value: 150, name: "民非企单位" },
      //   { value: 180, name: "基金会" },
      // ];
      // let title = "";
      let legend = {
        orient: "vertical",
        top: "35%",
        padding: 0,
        right: "10%",
        icon: "circle",
        itemGap: 3,
        textStyle: {
          color: "#8C8C8C",
          fontFamily: "PingFang-SC-Regular, PingFang-SC",
          fontWeight: 400,
          lineHeight: 17,
        },
      };
      let pieId = "standingbookpieChartstwo";
      let data = {
        color: color,
        dataArr: dataArr,
        // title: title,
        legend: legend,
        pieId: pieId,
        roseType: "radius",
        radius: ["30%", "70%"],
        position: "center",
        selectedMode: "",
      };
      this.pieData.data2 = data;
    },
    pieDatadeal(list) {
      let arr = [];
      this.dict?.type?.organization_catagroy?.map((tig) => {
        list.map((item) => {
          if (item.originType == tig.value) {
            let obj = {
              value: item.num,
              name: tig.label,
              originType: item.originType,
            };
            arr.push(obj);
          }
        });
      });
      return arr;
    },
    // 饼图点击事件
    clickPie(value) {
      if (this.fatherPielist.length > 0) {
        this.fatherPielist.map((item) => {
          if (item.originType == value.data.originType) {
            if (item.innerList.length > 0) {
              let arr = this.pieDatadeal(item.innerList);
              // this.resetpieData("2");
              this.getPiedata2(arr);
            } else {
              // this.resetpieData("2");
              this.getPiedata2([]);
            }
          }
        });
      } else {
        this.getPiedata2([]);
      }
    },
    /* 表格按钮 */
    // 提交
    handlerReported(row) {
      this.showModel("detail", row, "report");
    },
    // 编辑
    handlerEdit(row) {
      this.showModel("detail", row, "edit");
    },
    // 审核
    handerAudit(row) {
      this.showModel("detail", row, "audit");
    },
    // 确认
    handleComit(row) {
      this.showModel("detail", row, "comit");
    },
    // 上报
    handleUp(row) {
      this.showModel("detail", row, "up");
    },
    // 查看
    handlerLook(row) {
      this.showModel("detail", row, "look");
    },
    // 弹窗
    showModel(name, params, way) {
      this.modelName = name;
      this.modelWay = way;
      if (name == "detail") {
        this.id = params.id || "";
      } else if (name == "bulk") {
        this.id = "bulk1";
      }
      setTimeout(() => {
        this.show = true;
      }, 200);
    },
    close(status) {
      this.show = false;
      setTimeout(() => {
        if (status) this.handlerSearchDetail();
      }, 200);
    },
  },
};
</script>

<style lang="scss" scoped>
.standingbook-common {
  width: 100%;
  ::v-deep .el-card__header {
    border-bottom: none;
  }
  // .box-card {
  .clearfix {
    height: 22px;
    width: 100%;
    margin-bottom: 20px;
    span {
      opacity: 0.8;
    }
  }
  span {
    &:nth-child(1) {
      font-size: 20px;
      font-weight: 600;
      color: #333333;
    }
  }
  // }
}
</style>
